#!/usr/bin/env python
# -*- coding: utf-8 -*-

import StringIO
import Image
from config import config

class Process(object):
    def __init__(self):
        self.conf = config()
        n = len(self.conf.cameras)
        self.connected = [False]*n
        self.transport = [None]*n
        
    def connect(self, im_id, transport):
        self.connected[im_id] = True
        self.transport[im_id] = transport
    
    def disconnect(self, im_id):
        self.connected[im_id] = False

    def processImage(self, img, im_id):
        if self.connected[im_id]:
            if self.conf.cameras[im_id]['resize_w']:
                try:
                    im = Image.open(StringIO.StringIO(img))
                except:
                    print "Bad image"
                else:
                    im_downsize = im.resize((self.conf.cameras[im_id]['resize_w'],
                                             self.conf.cameras[im_id]['resize_h']),
                                            Image.ANTIALIAS)
                    f = StringIO.StringIO()
                    im_downsize.save(f, "JPEG", quality = self.conf.cameras[im_id]['quality'])
                    im_data = f.getvalue()
            else:
                im_data = img
            self.transport[im_id].write("""\r
--boundarydonotcross\r
Content-Type: image/jpeg\r
Content-Length: """ + str(len(im_data)) + """\r
X-Timestamp: 0.000000\r
\r
""")
            self.transport[im_id].write(im_data)